// 请求基本路径
export const BASE_URL = 'http://36.138.43.18:8085'
// export const BASE_URL = 'http://172.16.118.161:8085'

export function intervalTime(endTime) {
	// var startTime = new Date().getTime(); //计算当前时间戳
	var timestamp = (Date.parse(new Date())) / 1000; //计算当前时间戳 (毫秒级)
	var date1 = timestamp; //开始时间
	var date2 = (Date.parse(new Date(endTime))) / 1000; //结束时间
	// var date3 = date2.getTime() - date1.getTime(); //时间差的毫秒数
	var date3 = (date1 - date2) * 1000; //时间差的毫秒数
	//计算出相差天数
	var days = Math.floor(date3 / (24 * 3600 * 1000));
	//计算出小时数
	var leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000));
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000));
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);



	if (days == 0 && hours != 0) {
		return hours + "小时"
	} else if (days == 0 && hours == 0) {
		return '不久'
	} else {
		return days + "天 " + hours + "小时"
	}
	// return   days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒"
}

// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}


// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments,
		flag = true,
		i = 1;
	str = str.replace(/%s/g, function() {
		var arg = args[i++];
		if (typeof arg === 'undefined') {
			flag = false;
			return '';
		}
		return arg;
	});
	return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
	if (!str || str == "undefined" || str == "null") {
		return "";
	}
	return str;
}

// 数据合并
export function mergeRecursive(source, target) {
	for (var p in target) {
		try {
			if (target[p].constructor == Object) {
				source[p] = mergeRecursive(source[p], target[p]);
			} else {
				source[p] = target[p];
			}
		} catch (e) {
			source[p] = target[p];
		}
	}
	return source;
};


/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName];
		var part = encodeURIComponent(propName) + "=";
		if (value !== null && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']';
						var subPart = encodeURIComponent(params) + "=";
						result += subPart + encodeURIComponent(value[key]) + "&";
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&";
			}
		}
	}
	return result
}

// 验证是否为blob格式
export async function blobValidate(data) {
	try {
		const text = await data.text();
		JSON.parse(text);
		return false;
	} catch (error) {
		return true;
	}
}


export function formatNumber(numberStr) {
	try {
		let number = parseFloat(numberStr);

		if (isNaN(number)) {
			throw new Error("Invalid number format: " + numberStr);
		}

		// 保留一位小数并向下取整
		let roundedNumber = Math.trunc((number * 1000).toFixed(3)) / 1000;

		// 如果结果为0或-0，返回字符串"0"
		if (roundedNumber === 0) {
			return 0;
		}

		return roundedNumber;
	} catch (e) {
		console.error(e.message);
		return null;
	}
}

export function formatNumber2(numberStr) {
	try {
		let number = parseFloat(numberStr);

		if (isNaN(number)) {
			throw new Error("Invalid number format: " + numberStr);
		}

		// 保留一位小数并向下取整
		let roundedNumber = Math.trunc((number * 100).toFixed(2)) / 100;

		// 如果结果为0或-0，返回字符串"0"
		if (roundedNumber === 0) {
			return 0;
		}

		return roundedNumber;
	} catch (e) {
		console.error(e.message);
		return null;
	}
}


export function subtractAndAssign(a, b) {
  // 尝试将 a 和 b 转换为数字
  a = parseFloat(a)
  b = parseFloat(b)

  // 检查转换后是否为有效的数字
  if (isNaN(a) || isNaN(b)) {
    throw new TypeError('Arguments must represent valid numbers.');
  }

  // 保留两位小数并向下取整（避免浮点数精度问题）
  a = Math.floor(a * 100) / 100;
  b = Math.floor(b * 100) / 100;

  // 执行减法并保证结果非负
  a = Math.max(0, a - b);

  // 返回更新后的 a，保留一位小数
  return parseFloat(a.toFixed(2));
}